﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Configuration;
using umbraco.BusinessLogic;

namespace uREST.Core.PackageActions
{
    /// <summary>
    /// This Package action will Add a Reserved Url to the web.config
    /// </summary>
    public class AddUmbracoReservedUrl : AbstractPackageAction
    {
        /// <summary>
        /// This Alias must be unique and is used as an identifier that must match 
        /// the alias in the package action XML
        /// </summary>
        /// <returns>The Alias in string format</returns>
        public override string Alias()
        {
            return "uREST_AddUmbracoReservedUrl";
        }

        /// <summary>
        /// Append the xmlData node to the web.config file
        /// </summary>
        /// <param name="packageName">Name of the package that we install</param>
        /// <param name="xmlData">The data that must be appended to the web.config file</param>
        /// <returns>True when succeeded</returns>
        public override bool Execute(string packageName, System.Xml.XmlNode xmlData)
        {
            //Set result default to false
            bool result = false;

            //Get attribute values of xmlData
            string url;
            if (!TryGetAttribute(xmlData, "url", out url)) return result;

            try
            {
                var reservedPathsString = ConfigurationManager.AppSettings["umbracoReservedUrls"];
                if (string.IsNullOrEmpty(reservedPathsString))
                    return result;

                var reservedPathsList = new List<string>(reservedPathsString.Split(','));
                if (reservedPathsList.Contains(url))
                    return result;

                reservedPathsList.Add(url);

                Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
                if (config == null)
                    return result;

                var reservedPathsSetting = config.AppSettings.Settings["umbracoReservedUrls"];
                if (reservedPathsSetting == null)
                    return result;

                reservedPathsSetting.Value = string.Join(",", reservedPathsList.ToArray());
                config.Save();

                result = true;
            }
            catch (Exception e)
            {
                //Log error message
                string message = "Error at execute AddUmbracoReservedUrl package action: " + e.Message;
                Log.Add(LogTypes.Error, GetUser(), -1, message);
            }

            return result;
        }

        /// <summary>
        /// Removes the xmlData node from the web.config file
        /// </summary>
        /// <param name="packageName">Name of the package that we install</param>
        /// <param name="xmlData">The data that must be appended to the web.config file</param>
        /// <returns>True when succeeded</returns>
        public override bool Undo(string packageName, System.Xml.XmlNode xmlData)
        {
            //Set result default to false
            bool result = false;

            //Get attribute values of xmlData
            string url;
            if (!TryGetAttribute(xmlData, "url", out url)) return result;

            try
            {
                var reservedPathsString = ConfigurationManager.AppSettings["umbracoReservedUrls"];
                if (string.IsNullOrEmpty(reservedPathsString))
                    return result;

                var reservedPathsList = new List<string>(reservedPathsString.Split(','));
                if (!reservedPathsList.Remove(url))
                    return result;

                Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
                if (config == null)
                    return result;

                var reservedPathsSetting = config.AppSettings.Settings["umbracoReservedUrls"];
                if (reservedPathsSetting == null)
                    return result;

                reservedPathsSetting.Value = string.Join(",", reservedPathsList.ToArray());
                config.Save();

                result = true;
            }
            catch (Exception e)
            {
                //Log error message
                string message = "Error at undo AddUmbracoReservedUrl package action: " + e.Message;
                Log.Add(LogTypes.Error, GetUser(), -1, message);
            }

            return result;
        }
    }
}
